import { gql } from '@apollo/client'
import { FC, useRef } from 'react'
import { generatePath, useNavigate } from 'react-router-dom'

import {
  Avatar,
  Button,
  ButtonLink,
  Chip,
  DialogRef,
  Icon,
  Skeleton,
  Typography,
} from '~/components/designSystem'
import { IntegrationsPage } from '~/components/layouts/Integrations'
import { WarningDialog } from '~/components/WarningDialog'
import { addToast } from '~/core/apolloClient'
import { CountryCodes } from '~/core/constants/countryCodes'
import { IntegrationsTabsOptionsEnum } from '~/core/constants/tabsOptions'
import { intlFormatNumber } from '~/core/formats/intlFormatNumber'
import {
  INTEGRATIONS_ROUTE,
  ORGANIZATION_INFORMATIONS_ROUTE,
  TAXES_SETTINGS_ROUTE,
} from '~/core/router'
import {
  GocardlessForCreateAndEditSuccessRedirectUrlFragmentDoc,
  useGetTaxesForTaxManagementIntegrationDetailsPageQuery,
  useLagoTaxManagementIntegrationsSettingQuery,
  useRemoveTaxManagementIntegrationMutation,
} from '~/generated/graphql'
import { useInternationalization } from '~/hooks/core/useInternationalization'
import { usePermissions } from '~/hooks/usePermissions'
import LagoTaxManagement from '~/public/images/lago-tax-management.svg'
import { PageHeader } from '~/styles'

gql`
  query lagoTaxManagementIntegrationsSetting {
    organization {
      id
      country
      euTaxManagement
    }
  }

  query getTaxesForTaxManagementIntegrationDetailsPage {
    taxes(page: 1, limit: 1000, order: "rate", autoGenerated: true) {
      collection {
        id
        code
        name
        rate
      }
    }
  }

  mutation removeTaxManagementIntegration($input: UpdateOrganizationInput!) {
    updateOrganization(input: $input) {
      id
      euTaxManagement
    }
  }

  ${GocardlessForCreateAndEditSuccessRedirectUrlFragmentDoc}
`

const TaxItem: FC<{ name: string; code: string; rate: number }> = ({ name, code, rate }) => {
  const { translate } = useInternationalization()

  return (
    <div className="flex min-h-18 flex-row items-center justify-between gap-3 py-2 shadow-b">
      <div className="flex flex-1 items-center gap-3">
        <Avatar size="big" variant="connector">
          <Icon size="medium" name="percentage" color="dark" />
        </Avatar>
        <div>
          <Typography color="textSecondary" variant="bodyHl" noWrap>
            {name}
          </Typography>
          <Typography variant="caption" noWrap>
            {code}
          </Typography>
        </div>
      </div>
      <Chip className="ml-auto" label={translate('text_657078c28394d6b1ae1b9755')} />
      <Typography variant="body" className="basis-16" color="grey700" align="right">
        {intlFormatNumber(rate / 100, {
          style: 'percent',
        })}
      </Typography>
    </div>
  )
}

const LagoTaxManagementIntegration = () => {
  const navigate = useNavigate()
  const { translate } = useInternationalization()
  const { hasPermissions } = usePermissions()
  const deleteConnectionRef = useRef<DialogRef>(null)

  const { data: organizationData, loading: organizationLoading } =
    useLagoTaxManagementIntegrationsSettingQuery()
  const { data: taxesData, loading: taxesLoading } =
    useGetTaxesForTaxManagementIntegrationDetailsPageQuery()

  const [deleteConnexion] = useRemoveTaxManagementIntegrationMutation({
    onCompleted({ updateOrganization }) {
      if (updateOrganization) {
        addToast({
          message: translate('text_657078c28394d6b1ae1b981d'),
          severity: 'success',
        })
      }
    },
  })

  const organization = organizationData?.organization
  const isConnectionEstablished = organization?.euTaxManagement
  const loading = organizationLoading || taxesLoading

  return (
    <>
      <PageHeader.Wrapper withSide>
        <PageHeader.Group>
          <ButtonLink
            to={generatePath(INTEGRATIONS_ROUTE, {
              integrationGroup: IntegrationsTabsOptionsEnum.Lago,
            })}
            type="button"
            buttonProps={{ variant: 'quaternary', icon: 'arrow-left' }}
          />
          {loading ? (
            <Skeleton variant="text" className="w-30" />
          ) : (
            <Typography variant="bodyHl" color="textSecondary">
              {translate('text_657078c28394d6b1ae1b9713')}
            </Typography>
          )}
        </PageHeader.Group>
        {hasPermissions(['organizationIntegrationsDelete']) && (
          <Button
            variant="secondary"
            disabled={loading}
            onClick={deleteConnectionRef.current?.openDialog}
          >
            {translate('text_657078c28394d6b1ae1b971b')}
          </Button>
        )}
      </PageHeader.Wrapper>

      <IntegrationsPage.Header
        isLoading={loading}
        integrationLogo={<LagoTaxManagement />}
        integrationName={translate('text_657078c28394d6b1ae1b9713')}
        integrationChip={
          isConnectionEstablished ? translate('text_62b1edddbf5f461ab97127ad') : undefined
        }
        integrationDescription={translate('text_657078c28394d6b1ae1b971f')}
      />

      <IntegrationsPage.Container>
        <section>
          <IntegrationsPage.Headline label={translate('text_657078c28394d6b1ae1b9725')} />

          {loading && <IntegrationsPage.ItemSkeleton />}
          {!loading && (
            <>
              <IntegrationsPage.DetailsItem
                icon="globe"
                label={translate('text_657078c28394d6b1ae1b9765')}
                value={
                  (!!organization?.country && CountryCodes[organization?.country]) || undefined
                }
              />
              {hasPermissions(['organizationView']) && (
                <Typography
                  className="flex h-12 items-center justify-start"
                  variant="caption"
                  html={translate('text_657078c28394d6b1ae1b9737', {
                    href: ORGANIZATION_INFORMATIONS_ROUTE,
                  })}
                />
              )}
            </>
          )}
        </section>

        <section>
          <IntegrationsPage.Headline label={translate('text_657078c28394d6b1ae1b9743')}>
            {hasPermissions(['organizationTaxesView']) && (
              <Button
                variant="quaternary"
                disabled={loading}
                onClick={() => {
                  navigate(TAXES_SETTINGS_ROUTE)
                }}
              >
                {translate('text_657078c28394d6b1ae1b973d')}
              </Button>
            )}
          </IntegrationsPage.Headline>

          {loading && <IntegrationsPage.ItemSkeleton />}
          {!loading &&
            taxesData?.taxes?.collection.map((tax) => (
              <TaxItem key={tax.id} name={tax.name} code={tax.code} rate={tax.rate} />
            ))}
        </section>
      </IntegrationsPage.Container>

      <WarningDialog
        ref={deleteConnectionRef}
        title={translate('text_657078c28394d6b1ae1b9707')}
        description={translate('text_657078c28394d6b1ae1b970d')}
        continueText={translate('text_657078c28394d6b1ae1b971b')}
        onContinue={async () => {
          await deleteConnexion({
            variables: {
              input: {
                euTaxManagement: false,
              },
            },
          })

          navigate(
            generatePath(INTEGRATIONS_ROUTE, {
              integrationGroup: IntegrationsTabsOptionsEnum.Lago,
            }),
          )
        }}
      />
    </>
  )
}

export default LagoTaxManagementIntegration
